package com.gams.websocket.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Websocket 服务端
 */
@Slf4j
@Component
public class WebsocketServer implements InitializingBean
{


    @Autowired
    private WebSocketServerHandler clientHandler;

    @Override
    public void afterPropertiesSet()
    {
        new Thread(() ->
        {
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try
            {
                ServerBootstrap b = new ServerBootstrap();
                b.group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer<SocketChannel>()
                        {
                            @Override
                            protected void initChannel(SocketChannel ch)
                            {
                                ch.pipeline()
                                        .addLast("http-codec", new HttpServerCodec())
                                        .addLast("chunked-write", new ChunkedWriteHandler())
                                        .addLast("http-aggregator", new HttpObjectAggregator(8192))
                                        .addLast("log-handler", new LoggingHandler(LogLevel.WARN))
                                        .addLast("ws-server-handler", new WebSocketServerProtocolHandler("/ws"))
                                        .addLast("server-handler", clientHandler);
                            }
                        });
                //端口配置5005
                Channel ch = b.bind(5001).sync().channel();
                System.out.println("start websocket success! 5001");
                ch.closeFuture().sync();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            } finally
            {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        }).start();

    }
}
